package com.guiwu.gteway.industryapp.Map;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.guiwu.gteway.industryapp.Api.GuiwuApi;
import com.guiwu.gteway.industryapp.Api.GuiwuApiCallback;
import com.guiwu.gteway.industryapp.Device.View.DeviceListFragment;
import com.guiwu.gteway.industryapp.Device.module.GateWay;
import com.guiwu.gteway.industryapp.Device.module.GateWayGroup;
import com.guiwu.gteway.industryapp.MainActivity;
import com.guiwu.gteway.industryapp.R;
import com.guiwu.gteway.industryapp.util.BaiduLocation;
import com.guiwu.gteway.industryapp.util.MyLog;
import com.guiwu.gteway.industryapp.util.PreferencesUtil;
import com.guiwu.gteway.industryapp.util.ProgressSimpleDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by 乔冠 on 2017/12/20. map页的fragment
 */

public class GuiwuMapFragment extends Fragment implements BaiduMap.OnMarkerClickListener,BaiduMap.OnMapClickListener {

    private static final String ARG_LOCATION = "location_args";

    private MapView mapView = null;
    private BaiduMap baiduMap = null;
    private BaiduLocation mBaiduLocation;
    private ProgressSimpleDialog getGateWayGroupsDialog;
    private List<GateWayGroup> gateWayGroups;
    private List<GateWay> allGateWays = new ArrayList<>();
    Map<String ,List<GateWay>> apikeyMap = new HashMap<>();
    private static final String TAG = "GuiwuMapFragment";

    //初始化bitmap信息
    BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromResource(R.mipmap.marker64);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void initGateWay(){
        getGateWayGroupsDialog = new ProgressSimpleDialog(getContext());
        getGateGroups();
    }

    //marker
    public void addOverLay(List<GateWay> gateWays){
        baiduMap.clear();
        MarkerOptions options;
        Marker marker;
        LatLng ll = null;
        for (GateWay gateWay : gateWays){
            ll = new LatLng(gateWay.getGateWayLocation().getLatitude()
                                    ,gateWay.getGateWayLocation().getLongitude());
            options = new MarkerOptions()
                            .position(ll)
                            .icon(markerIcon)
                            .zIndex(9)
                            .draggable(false)
                            .animateType(MarkerOptions.MarkerAnimateType.grow);
            marker = (Marker) baiduMap.addOverlay(options);
            Bundle bundle = new Bundle();
            bundle.putParcelable("gateWayInfo" , gateWay);
            marker.setExtraInfo(bundle);
        }
        if (ll != null){
            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.setMapStatus(msu);
        }
    }




    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.map_layout,container,false);
        //map视图创建
        mapView = v.findViewById(R.id.bmapView);
        baiduMap = mapView.getMap();
        baiduMap.setOnMarkerClickListener(this);
        return v;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
       // mBaiduLocation.stopLocation();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        initGateWay();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    private void setMapLocation(){

        mBaiduLocation = new BaiduLocation(getContext(),baiduMap,mapView,true);

    }

    private void initDate(){
        apikeyMap.clear();
        allGateWays.clear();
    }

    /**
     * 获取网关组
     */
    public void getGateGroups(){
        getGateWayGroupsDialog.showPorgressDialog("正在获取用户设备");
        int userId = PreferencesUtil.getInstance(getContext()).getInt("userId",0);
        GuiwuApi.getGateWayGroup(String.valueOf(userId), new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG,"登录返回数据" + response);
                try {
                    JsonObject resp = new JsonParser().parse(response).getAsJsonObject();
                    int errno = resp.get("errno").getAsInt();
                    if (errno == 0){
                        JsonArray jsonArray = resp.getAsJsonArray("data");
                        Gson gson = new Gson();
                        gateWayGroups = gson.fromJson(jsonArray, new TypeToken<List<GateWayGroup>>() {}.getType());
                        queryGatWayState(gateWayGroups);
                    }else
                        Log.i(TAG,"返回错误码");
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    Log.i(TAG,"json转换出错");
                }
            }
            @Override
            public void onFailed(Exception e) {
                getGateWayGroupsDialog.closeProgressDialog();
            }
        });
    }

    //查询网关在线状态
    private void queryGatWayState(List<GateWayGroup> gateWayGroups){
        MyLog.i(TAG,"查询这些网关" + gateWayGroups.toString());
      //  List<String> ids = new ArrayList<>();
        initDate();
        List<String> apikList = new ArrayList<>();
       //  apikeyMap = new HashMap<>();
      //  String apiKey = null;
//        final List<GateWay> allGateWay = new ArrayList<>();
        for (GateWayGroup gateWayGroup : gateWayGroups){
            for (GateWay gateWay : gateWayGroup.getGateWays()){
                String apiKey = gateWay.getApiKey();
                if (!apikeyMap.containsKey(apiKey)){
                    apikeyMap.put(apiKey,new ArrayList<GateWay>());
                    apikeyMap.get(apiKey).add(gateWay);
                }else {
                    apikeyMap.get(apiKey).add(gateWay);
                }
                gateWay.setFromGroup(gateWayGroup.getGroupName());
                allGateWays.add(gateWay);
            }
        }

        if (apikeyMap.size() == 0){
            getGateWayGroupsDialog.closeProgressDialog();
            return;
        }

        for (String apikey : apikeyMap.keySet()){
            List<String> ids = new ArrayList<>();
            for (GateWay gateWay : apikeyMap.get(apikey)){
                ids.add(gateWay.getGateWayId());
            }
            sendRequest(apikey,ids);
        }

//        for (int i = 0;i< gateWayGroups.size() ;i++){
//            for (int j = 0; j< gateWayGroups.get(i).getGateWays().size() ; j++){
//                GateWay gateWay = gateWayGroups.get(i).getGateWays().get(j);
//                ids.add(gateWay.getGateWayId());
//                gateWay.setFromGroup(gateWayGroups.get(i).getGroupName());
//                allGateWays.add(gateWay);
//            }
//            if (gateWayGroups.get(i).getGateWays().size() > 0 && apiKey == null)
//                apiKey = gateWayGroups.get(i).getGateWays().get(0).getApiKey();
//        }
//        if (apiKey == null)
//            return;
    }

    private void sendRequest(final String apiKey,List<String> ids){
        GuiwuApi.queryGateWaySate(apiKey,ids,new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG, "获取网关状态成功: " + response);
                pressData(response, apikeyMap.get(apiKey));

            }

            @Override
            public void onFailed(Exception e) {
                MyLog.i(TAG , "获取网关状态失败" + e.getMessage());
                getGateWayGroupsDialog.closeProgressDialog();

            }
        });
    }




    private void pressData(String jsonResponse ,final List<GateWay> gateWays){
        try{
            JsonObject jsonObject = new JsonParser().parse(jsonResponse).getAsJsonObject();
            int erron = jsonObject.get("errno").getAsInt();
            int count;
            if (erron == 0){
                JsonObject ob2 = jsonObject.get("data").getAsJsonObject();
                count = ob2.get("total_count").getAsInt();
                JsonArray array = ob2.get("devices").getAsJsonArray();
                for (GateWay per :gateWays){
                    for (JsonElement element : array){
                        JsonObject perObject =  element.getAsJsonObject();
                        if (perObject.get("id").getAsInt() == Integer.parseInt(per.getGateWayId())){
                            boolean isOnline = perObject.get("online").getAsBoolean();
                            per.setIsOnline(isOnline ? 1 :0);
                        }
                    }
                }
                MyLog.i(TAG,"网关状态解析成功" + gateWays);
                addOverLay(allGateWays);
            }else {
                MyLog.i(TAG, "网关状态解析出现问题：" + jsonObject.get("error").getAsString());
            }
        }catch (JsonParseException e){
            MyLog.i(TAG, "网关状态解析出现问题：" + e.getMessage());
        }
        boolean isComplate = true;
        for (GateWay gateWay : allGateWays){
            if (gateWay.getIsOnline() == -1)
                isComplate = false;
        }
        if (isComplate){
            getGateWayGroupsDialog.closeProgressDialog();
            MainActivity activity = (MainActivity)getActivity();
            activity.setmGateWayGroups(gateWayGroups);
            ((DeviceListFragment)activity.getFragments().get(1)).updateUI();
        }

    }

    //marker点击
    @Override
    public boolean onMarkerClick(Marker marker) {
        Bundle bundle = marker.getExtraInfo();
        GateWay gateWay = bundle.getParcelable("gateWayInfo");
        //将信息显示在界面上
        TextView tv = new TextView(getContext());
        tv.setBackgroundResource(R.mipmap.popup);
        tv.setPadding(20,10,20,20);
        tv.setTextColor(getResources().getColor(R.color.blue));
        if (gateWay == null)
            return true;
        if (gateWay.getIsOnline() == 1){
            tv.setTextColor(getResources().getColor(R.color.blue));
            tv.setText(gateWay.getGateWayName());
        }
        else {
            tv.setTextColor(getResources().getColor(R.color.red));
            String show = gateWay.getGateWayName() +"("+ getResources().getString(R.string.ds_isOnline_false) + ")";
            tv.setText(show);
        }
        tv.setGravity(Gravity.CENTER);
        LatLng latLng = new LatLng(gateWay.getGateWayLocation().getLatitude()
                                    ,gateWay.getGateWayLocation().getLongitude());
        InfoWindow.OnInfoWindowClickListener listener = new InfoWindow.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick() {
                //隐藏inforWindow
                baiduMap.hideInfoWindow();
            }
        };

        InfoWindow infoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(tv),
                                    latLng,-47,listener);
        baiduMap.showInfoWindow(infoWindow);
        return true;
    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }
}
